package com.zxw.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @projectName: util-cloud
 * @package: com.zxw
 * @className: File2
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/8/29 18:02
 * @version: 1.0
 */
@RestController
@RequestMapping("/video")
public class File2 {
    String videoPath = "D:/ProjectFile/bmp/profile/upload/2023/08/29/8月28日(1)_20230829161806A002.mp4"; // Update with the actual video file path

    @GetMapping("/stream")
    public ResponseEntity<StreamingResponseBody> streamVideo() throws IOException {
        Resource videoResource = new FileSystemResource(videoPath);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(videoResource.contentLength());
        StreamingResponseBody responseBody = outputStream -> {
            try (InputStream videoStream = videoResource.getInputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = videoStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                // Handle exception
            }
        };

        return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
    }


}
